import {
  Category,
  CategoryDocument,
} from '@app/database/schemas/category.schema';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class CategoriesService {
  constructor(
    @InjectModel('Category')
    private readonly categoryModel: Model<CategoryDocument>,
  ) {}

  create(category: Category) {
    return this.categoryModel.create(category);
  }

  async findAll(query: any) {
    let { size, currentPage } = query || {};
    size = Number(size);
    currentPage = Number(currentPage);
    const res = await this.categoryModel
      .find()
      .skip((currentPage - 1) * size)
      .limit(size)
      .sort({ _id: -1 });
    const total = await this.categoryModel.countDocuments();
    return {
      items: res,
      total,
    };
  }

  findOne(id: string) {
    return this.categoryModel.findOne({ _id: id });
  }

  update(id: string, category: Category) {
    return this.categoryModel.updateOne({ _id: id }, category);
  }

  remove(id: string) {
    return this.categoryModel.deleteOne({ _id: id });
  }

  option() {
    return {
      title: '图书分类列表',
      descriptions: '显示和处理图书分类列表',
      items: [
        {
          label: '分类名称',
          prop: 'name',
          type: 'input',
        },
      ],
    };
  }
}
